package com.exit66.jukebox.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;

import com.exit66.jukebox.util.CommandParser;
import com.exit66.jukebox.Options;
import com.exit66.jukebox.util.Base64;

public class BlueVadeTemplateServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4307790324409963122L;

	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		if (verifyLogin(req, res)) {
			PrintWriter out = res.getWriter();
	        CommandParser cp = new CommandParser();
	        ServletContext context = this.getServletContext();
	        String fileName = context.getRealPath(req.getServletPath());
	        Properties query = getQueryProps(req);
	        cp.processForm(query);
	        cp.processTemplateFile(fileName, query);
	        out.print(cp.getOutput());
			out.close();
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doGet(req, res);
	}
	
	protected Properties getQueryProps(HttpServletRequest req) {
		Properties query = new Properties();
		Enumeration iter = req.getParameterNames();
		
		while (iter.hasMoreElements()) {
			String key = iter.nextElement().toString();
			Object value = req.getParameter(key);
			query.setProperty(key, value.toString());
		}
		
		return query;
	}
	
	protected boolean verifyLogin(HttpServletRequest req, HttpServletResponse res) {
		boolean mustLogin = false;
		
        if (Options.getAdminPassword().equals("")) {
            mustLogin = false;
        }
        else if (req.getHeader("authorization") != null) {
            try {
                String encoded = req.getHeader("authorization");
                encoded = encoded.substring(encoded.indexOf(" ") + 1);
                String decoded = new String(Base64.decode(encoded));
                decoded = decoded.substring(decoded.indexOf(":") + 1);
                if (!Options.verifyAdminPassword(decoded)) {
                    mustLogin = true;
                }
            }
            catch (Exception e) {
                mustLogin = true;
            }
        }
        else {
            mustLogin = true;
        }
        
        if (mustLogin) {
        	try {
	        	PrintWriter out = res.getWriter();
	        	res.setHeader("WWW-Authenticate", "Basic realm=\"Exit 66 Jukebox\"");
	        	res.setStatus(401);
	            out.print("<html><head><title>Exit 66 Jukebox</title></head><body>You must be logged in to access this area</body></html>");
	            out.close();
        	}
        	catch (Exception e) {
        		System.err.println(e);
        	}
        }
        
        return !mustLogin;
	}
	
}
